package demo2;

public class HashBuck<K,V> {
    static class Node<K,V> {
        public K key;
        public V value;
        public Node<K,V> next;

        public Node(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }

    public Node<K,V>[] array;
    public int usedSize;
    public static final double loadFactor = 0.7;

    public HashBuck() {
        this.array = (Node<K,V>[])new Node[10];
    }
    public void put(K key, V value) {
        int index = key.hashCode() % array.length;
        Node<K,V> cur = array[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                cur.value = value;
                return;
            }
            cur = cur.next;
        }
        Node<K,V> node = new Node<>(key,value);
        node.next = array[index];
        array[index] = node;
        usedSize++;
        if (calculateLoadFactor() >= loadFactor) {
            resize();
        }
    }

    private void resize() {
        Node<K,V>[] newArray = (Node<K,V>[])new Node[2*array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            Node curNext = null;
            while (cur != null) {
                curNext = cur.next;
                int index = cur.key.hashCode() % newArray.length; //找到了在新数组当中的位置
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        this.array = newArray;
    }

    public double calculateLoadFactor() {
        return (usedSize*1.0) / array.length;
    }

    public V get(K key) {
        int index = key.hashCode() % array.length;
        Node<K,V> cur = array[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                return cur.value;
            }
            cur = cur.next;
        }
        throw new RuntimeException("找不到Key所对应的Value");
    }
}
